package cn.zyq.demo.service.sys.impl;


import cn.zyq.demo.beans.sys.SysAdmin;
import cn.zyq.demo.beans.sys.SysDictData;
import cn.zyq.demo.beans.sys.SysDictType;
import cn.zyq.demo.mapper.sys.SysDictDataMapper;
import cn.zyq.demo.mapper.sys.SysDictTypeMapper;
import cn.zyq.demo.service.sys.SysDictTypeService;
import cn.zyq.demo.system.common.BaseService;
import cn.zyq.demo.system.common.PageParam;
import cn.zyq.demo.system.config.redis.RedisService;
import cn.zyq.demo.system.ry.CacheConstants;
import cn.zyq.demo.system.ry.UserConstants;
import cn.zyq.demo.system.ry.util.DictUtils;
import cn.zyq.demo.system.ry.util.StringUtils;
import com.aliyun.oss.ServiceException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 字典类型表
 * 2023-05-12 20:14:08
 */

@Slf4j
@Service
public class SysDictTypeServiceImpl extends BaseService implements SysDictTypeService {
    @Autowired
    private SysDictTypeMapper sysDictTypeMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Override
    public PageInfo<SysDictType> list(PageParam pageParam, SysAdmin admin) {
        PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
        List<SysDictType> dbList = this.sysDictTypeMapper.list(pageParam.getKv());
        return new PageInfo<>(dbList);
    }

    @Override
    public void add(SysDictType param, SysAdmin admin) {
        this.setCreateBaseData(param, admin);
        this.sysDictTypeMapper.insertSelective(param);
    }

    @Override
    public void update(SysDictType param, SysAdmin admin) {
        Integer id = param.getSysDictTypeID();
        this.setUpdateBaseData(param, admin);
        this.sysDictTypeMapper.updateByPrimaryKeySelective(param);
    }

    @Override
    public void del(String serviceID, SysAdmin admin) {
        SysDictType dbInfo = this.detail(serviceID);
        Integer id = dbInfo.getSysDictTypeID();
        this.deleteLogic(id, admin, this.sysDictTypeMapper);
    }

    @Override
    public SysDictType detail(String serviceID, SysAdmin admin) {
        return this.detail(serviceID);
    }

    @Override
    public SysDictType detail(String serviceID) {
        SysDictType dbInfo = this.getByServiceID(serviceID, SysDictType.class, this.sysDictTypeMapper);
        this.checkLogicExist(dbInfo);
        return dbInfo;
    }

    /**
     * 根据条件分页查询字典类型
     *
     * @param param 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeList(PageParam param) {
        return sysDictTypeMapper.selectDictTypeList(param.getKv());
    }

    /**
     * 根据字典类型ID查询信息
     *
     * @param dictId 字典类型ID
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeById(Integer dictId) {
        return sysDictTypeMapper.selectByPrimaryKey(dictId);
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public boolean checkDictTypeUnique(SysDictType dict) {
        Integer dictId = StringUtils.isNull(dict.getSysDictTypeID()) ? -1 : dict.getSysDictTypeID();
        SysDictType dictType = sysDictTypeMapper.checkDictTypeUnique(dict.getDictType());
        if (StringUtils.isNotNull(dictType) && !dictType.getSysDictTypeID().equals(dictId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 批量删除字典类型信息
     *
     * @param dictIds 需要删除的字典ID
     */
    @Override
    public void deleteDictTypeByIds(Integer[] dictIds) {
        for (Integer dictId : dictIds) {
            SysDictType dictType = selectDictTypeById(dictId);
            if (sysDictTypeMapper.countDictDataByType(dictType.getDictType()) > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
            sysDictTypeMapper.deleteByPrimaryKey(dictId);
            DictUtils.removeDictCache(dictType.getDictType());
            // redisService.deleteObject(getCacheKey(dictType.getDictType()));
        }
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    public static String getCacheKey(String configKey) {
        return CacheConstants.SYS_DICT_KEY + configKey;
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache() {
        clearDictCache();
        loadingDictCache();
    }

    @Override
    public void clearDictCache() {
        // Collection<String> keys = redisService.keys(CacheConstants.SYS_DICT_KEY + "*");
        DictUtils.clearDictCache();
    }

    @Override
    public void loadingDictCache() {
        SysDictData dictData = new SysDictData();
        dictData.setStatus("0");
        Map<String, List<SysDictData>> dictDataMap = this.sysDictDataMapper.selectDictDataList(dictData).stream().collect(Collectors.groupingBy(SysDictData::getDictType));
        for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet()) {
            DictUtils.setDictCache(entry.getKey(), entry.getValue().stream().sorted(Comparator.comparing(SysDictData::getDictSort)).collect(Collectors.toList()));
        }
    }

    /**
     * 根据所有字典类型
     *
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeAll() {
        return sysDictTypeMapper.selectAll();
    }

    @Override
    public List<SysDictData> selectDictDataByType(String dictType) {
        List<SysDictData> dictDatas = DictUtils.getDictCache(dictType);
        if (StringUtils.isNotEmpty(dictDatas))
        {
            return dictDatas;
        }
        dictDatas = sysDictDataMapper.selectDictDataByType(dictType);
        if (StringUtils.isNotEmpty(dictDatas))
        {
            DictUtils.setDictCache(dictType, dictDatas);
            return dictDatas;
        }
        return null;
    }
}
